package com.zhaungjie.base.utils;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * 抖动缓冲执行器
 *
 * @author zhuangjie
 * @date 2024/01/19
 */
public class DebounceExecutor {
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    private ScheduledFuture<?> lastScheduledTask = null;
    private final int delay; // 防抖延迟时间，单位毫秒

    public DebounceExecutor(int delay) {
        this.delay = delay;
    }

    public synchronized void debounce(Runnable runnable) {
        if (lastScheduledTask != null && !lastScheduledTask.isDone()) {
            lastScheduledTask.cancel(false);
        }
        lastScheduledTask = scheduler.schedule(runnable, delay, TimeUnit.MILLISECONDS);

    }

    public void shutdown() {
        scheduler.shutdown();
    }

    public static void main(String[] args) {
        DebounceExecutor debounceExecutor = new DebounceExecutor(500); // 500毫秒的防抖延迟

        // 模拟多次调用事件
        for (int i = 0; i < 10; i++) {
            debounceExecutor.debounce(()->{
                System.out.println("完成了");
            });
            // 假设触发事件的间隔比防抖时间短
            try {
                if (i == 4) {
                    Thread.sleep(600);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
